package com.gcxy.tour.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gcxy.tour.common.CommException;
import com.gcxy.tour.domain.UserInfo;
import com.gcxy.tour.service.UserService;

@WebServlet(urlPatterns = { "/user/login.do" })
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = -2338769502572066021L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("servlet执行");
		try {
			//1.抽取参数。封装为实体对象
			String usercode=req.getParameter("usercode");
			String password=req.getParameter("password");
			logger.debug("获取参数成功:{},{}",usercode,password);
			//2.类型转换
			logger.debug("类型转换成功");
			//3.数据校验
			if(usercode==null||usercode.length()<4||password==null||password.length()<6) {
				throw new CommException("账号或密码长度错误");
			}
			logger.debug("校验成功");
			//4.调用业务方法
			UserInfo userInfo= UserService.login(usercode,password);
			HttpSession session=req.getSession();
			session.setAttribute("user", userInfo);
			logger.debug("业务处理成功");
			//5.转发或者重定向
			req.getRequestDispatcher("Home.jsp").forward(req, resp);
		} catch (Exception e) {
			logger.error(e.getMessage());
			req.setAttribute("error", e.getMessage());
			req.getRequestDispatcher("/Register.jsp").forward(req, resp);
		}
	}



}
